<template>
  <div class="" style="padding: 15px 15px 0 15px">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="车牌号" prop="plateNumber">
          <el-input v-model="queryParams.plateNumber" placeholder="请输入车牌号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="司机姓名" prop="driverName">
          <el-input v-model="queryParams.driverName" placeholder="请输入司机姓名" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="车辆类型" prop="vehicleType">
          <el-select v-model="queryParams.vehicleType" placeholder="请选择车辆类型" clearable style="width: 200px">
            <el-option label="小型汽车" value="小型汽车" />
            <el-option label="大型汽车" value="大型汽车" />
            <el-option label="货车" value="货车" />
            <el-option label="客车" value="客车" />
          </el-select>
        </el-form-item>
        <el-form-item label="车辆状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="正常" :value="1" />
            <el-option label="停用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="hover">
      <!-- 工具栏 -->
      <div class="data-table__toolbar" style="position: relative">
        <div class="data-table__toolbar--actions">
          <el-button type="success" icon="plus" @click="handleAdd">新增</el-button>
          <el-button type="danger" icon="delete" :disabled="!selectedIds.length"
            @click="handleDelete(selectedIds.join(','))">批量删除</el-button>
          <el-button type="info" icon="download" @click="handleExport">导出</el-button>
        </div>
        <div>
          <div style="display: flex; align-items: center" class="moreBtn" @click="isShowBoxChange">
            <el-image style="width: 20px; height: 20px" :src="moreSrc" :fit="fit" />
            <el-icon>
              <CaretBottom />
            </el-icon>
          </div>
        </div>
        <div v-if="isShowBox" class="selectBox">
          <el-checkbox-group v-model="isTableShow" @change="checkBoxChange">
            <el-row>
              <el-col :span="8">
                <el-checkbox label="序号" :value="'序号'" />
              </el-col>
              <el-col :span="8">
                <el-checkbox label="车牌号" :value="'车牌号'" />
              </el-col>
              <el-col :span="8">
                <el-checkbox label="车辆品牌" :value="'车辆品牌'" />
              </el-col>
              <el-col :span="8">
                <el-checkbox label="车辆型号" :value="'车辆型号'" />
              </el-col>
              <el-col :span="8">
                <el-checkbox label="车辆类型" :value="'车辆类型'" />
              </el-col>
              <el-col :span="8">
                <el-checkbox label="车辆颜色" :value="'车辆颜色'" />
              </el-col>
              <el-col :span="8">
                <el-checkbox label="司机姓名" :value="'司机姓名'" />
              </el-col>
              <el-col :span="8">
                <el-checkbox label="司机电话" :value="'司机电话'" />
              </el-col>
              <el-col :span="8">
                <el-checkbox label="所属用户" :value="'所属用户'" />
              </el-col>
              <el-col :span="8">
                <el-checkbox label="创建时间" :value="'创建时间'" />
              </el-col>
              <el-col :span="8">
                <el-checkbox label="备注" :value="'备注'" />
              </el-col>
            </el-row>
          </el-checkbox-group>
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table ref="vehicleTableRef" v-loading="loading" :data="vehicleList" style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="isTableShow.includes('序号')" type="index" label="序号" width="60" align="center" />
        <el-table-column v-if="isTableShow.includes('车牌号')" label="车牌号" prop="carNumber" width="120" align="center" />

        <el-table-column v-if="isTableShow.includes('司机姓名')" label="司机姓名" prop="driverName" width="100"
          align="center" />
        <el-table-column v-if="isTableShow.includes('司机电话')" label="司机电话" prop="phone" width="120" align="center" />
        <el-table-column v-if="isTableShow.includes('所属用户')" label="所属用户" prop="userName" width="120" align="center" />

        <el-table-column v-if="isTableShow.includes('车辆品牌')" label="车辆品牌" prop="brand" width="100" align="center" />
        <el-table-column v-if="isTableShow.includes('车辆型号')" label="车辆型号" prop="model" width="120" align="center" />
        <el-table-column v-if="isTableShow.includes('车辆类型')" label="车辆类型" prop="vehicleType" width="100"
          align="center" />
        <el-table-column v-if="isTableShow.includes('车辆颜色')" label="车辆颜色" prop="color" width="80" align="center" />
        <el-table-column v-if="isTableShow.includes('创建时间')" label="创建时间" prop="createTime" width="180"
          align="center" />
        <el-table-column v-if="isTableShow.includes('备注')" label="备注" prop="remark" min-width="120"
          show-overflow-tooltip />
        <el-table-column fixed="right" label="操作" width="200" align="center">
          <template #default="scope">
            <el-button type="primary" link size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link size="small" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="handleQuery" />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" @close="handleCloseDialog">
      <el-form ref="vehicleFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="车牌号" prop="plateNumber">
              <el-input v-model="formData.plateNumber" placeholder="请输入车牌号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆品牌" prop="brand">
              <el-input v-model="formData.brand" placeholder="请输入车辆品牌" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆型号" prop="model">
              <el-input v-model="formData.model" placeholder="请输入车辆型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆类型" prop="vehicleType">
              <el-select v-model="formData.vehicleType" placeholder="请选择车辆类型" style="width: 100%">
                <el-option label="小型汽车" value="小型汽车" />
                <el-option label="大型汽车" value="大型汽车" />
                <el-option label="货车" value="货车" />
                <el-option label="客车" value="客车" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆颜色" prop="color">
              <el-input v-model="formData.color" placeholder="请输入车辆颜色" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发动机号" prop="engineNumber">
              <el-input v-model="formData.engineNumber" placeholder="请输入发动机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车架号" prop="vinNumber">
              <el-input v-model="formData.vinNumber" placeholder="请输入车架号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="司机姓名" prop="driverName">
              <el-input v-model="formData.driverName" placeholder="请输入司机姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="司机电话" prop="driverPhone">
              <el-input v-model="formData.driverPhone" placeholder="请输入司机电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属用户" prop="userId">
              <el-select v-model="formData.userId" placeholder="请选择所属用户" style="width: 100%" filterable>
                <el-option v-for="user in userOptions" :key="user.value" :label="user.label" :value="user.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio :value="1">正常</el-radio>
                <el-radio :value="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确定</el-button>
          <el-button @click="handleCloseDialog">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import VehicleAPI, { type VehiclePageQuery, type VehicleForm, type VehiclePageVO } from '@/api/system/vehicle.api'
import UserAPI from '@/api/system/user.api'
import { ElMessage, ElMessageBox } from 'element-plus'
import { CaretBottom } from '@element-plus/icons-vue'
import moreSrc from '@/assets/more.png'

defineOptions({
  name: 'Vehicle',
  inheritAttrs: false
})

// 响应式数据
const loading = ref(false)
const vehicleList = ref<VehiclePageVO[]>([])
const total = ref(0)
const selectedIds = ref<string[]>([])
const userOptions = ref<OptionType[]>([])
const fit = ref('cover')

// 列显示控制
const isShowBox = ref(false)
const isTableShow = ref([
  '序号',
  '车牌号',
  '车辆品牌',
  '车辆型号',
  '车辆类型',
  '司机姓名',
  '司机电话',
  '创建时间'
])

// 查询参数
const queryParams = ref<VehiclePageQuery>({
  pageNum: 1,
  pageSize: 10,
  cardId: '',
  clientName: '',
  isLower: true,
  userId: 1
})

// 对话框
const dialog = reactive({
  title: '新增车辆',
  visible: false
})

// 表单数据
const formData = ref<VehicleForm>({
  plateNumber: '',
  brand: '',
  model: '',
  vehicleType: '',
  color: '',
  engineNumber: '',
  vinNumber: '',
  driverName: '',
  driverPhone: '',
  userId: '',
  status: 1,
  remark: ''
})

// 表单验证规则
const rules = reactive({
  plateNumber: [{ required: true, message: '请输入车牌号', trigger: 'blur' }],
  vehicleType: [{ required: true, message: '请选择车辆类型', trigger: 'change' }],
  driverName: [{ required: true, message: '请输入司机姓名', trigger: 'blur' }],
  driverPhone: [
    { required: true, message: '请输入司机电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  userId: [{ required: true, message: '请选择所属用户', trigger: 'change' }]
})

// 表单引用
const queryFormRef = ref()
const vehicleFormRef = ref()
const vehicleTableRef = ref()

// 列显示控制相关方法
function isShowBoxChange() {
  isShowBox.value = !isShowBox.value
}

function checkBoxChange(val: string[]) {
  console.log(val)
  isTableShow.value = val
}

// 获取车辆列表
const getVehicleList = async () => {
  loading.value = true
  try {
    const { data } = await VehicleAPI.getPage(queryParams.value)
    console.log(data)
    vehicleList.value = data.data.records
    total.value = parseInt(data.data.total)
  } catch (error) {
    console.error('获取车辆列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取用户选项
const getUserOptions = async () => {
  try {
    const { data } = await UserAPI.getOptions()
    userOptions.value = data
  } catch (error) {
    console.error('获取用户选项失败:', error)
  }
}

// 查询
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getVehicleList()
}

// 重置查询
const handleResetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 新增
const handleAdd = () => {
  dialog.title = '新增车辆'
  dialog.visible = true
  resetForm()
}

// 编辑
const handleEdit = (row: VehiclePageVO) => {
  dialog.title = '编辑车辆'
  dialog.visible = true
  Object.assign(formData.value, row)
}

// 删除
const handleDelete = (ids: string) => {
  ElMessageBox.confirm('确认删除选中的车辆吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await VehicleAPI.deleteByIds(ids)
      ElMessage.success('删除成功')
      getVehicleList()
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

// 导出
const handleExport = async () => {
  try {
    await VehicleAPI.export(queryParams.value)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
  }
}

// 表格选择变化
const handleSelectionChange = (selection: VehiclePageVO[]) => {
  selectedIds.value = selection.map(item => item.id)
}

// 提交表单
const handleSubmit = () => {
  vehicleFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        if (formData.value.id) {
          await VehicleAPI.update(formData.value.id, formData.value)
          ElMessage.success('更新成功')
        } else {
          await VehicleAPI.create(formData.value)
          ElMessage.success('新增成功')
        }
        dialog.visible = false
        getVehicleList()
      } catch (error) {
        console.error('提交失败:', error)
      }
    }
  })
}

// 关闭对话框
const handleCloseDialog = () => {
  dialog.visible = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  vehicleFormRef.value?.resetFields()
  formData.value = {
    plateNumber: '',
    brand: '',
    model: '',
    vehicleType: '',
    color: '',
    engineNumber: '',
    vinNumber: '',
    driverName: '',
    driverPhone: '',
    userId: '',
    status: 1,
    remark: ''
  }
}

// 初始化
onMounted(() => {
  getVehicleList()
  getUserOptions()
})
</script>

<style lang="scss" scoped>
.search-container {
  margin-bottom: 20px;

  .search-buttons {
    margin-left: auto;
  }
}

.data-table__toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;

  &--actions {
    display: flex;
    gap: 8px;
  }
}

.moreBtn {
  padding: 5px 10px;
  border: #d8d4d4 1px solid;
  border-radius: 5px;
  cursor: pointer;
}

.moreBtn:hover {
  background-color: #f2f3f5;
}

.selectBox {
  position: absolute;
  background-color: #fff;
  border: #d8d4d4 1px solid;
  border-radius: 5px;
  padding: 10px 30px;
  z-index: 99;
  right: 0;
  top: 35px;
  width: 430px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
